﻿using XiangziProjectTemplete.Core.Common.HttpContextUser;
using XiangziProjectTemplete.Core.Extensions.Others;
using XiangziProjectTemplete.Core.IServices;
using XiangziProjectTemplete.Core.Model;
using XiangziProjectTemplete.Core.Model.CommonModel;
using XiangziProjectTemplete.Core.Model.Models;
using XiangziProjectTemplete.Core.Model.ParamModels;
using XiangziProjectTemplete.Core.Utility;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Collections.Generic;
using System.Threading.Tasks;
using System;
using XiangziProjectTemplete.Core.Model.ViewModels.XiangziProjectTemplete;
using XiangziProjectTemplete.Core.Common.Helper;

namespace XiangziProjectTemplete.Core.Api.Controllers
{
    /// <summary> 
    /// 角色工序查询视图 
    /// </summary> 
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Authorize(Permissions.Name)]
    public class V_ProcedureRoleController : ControllerBase
    {
        private readonly IV_ProcedureRoleServices _V_ProcedureRoleServices;
        private readonly IUser _user;
        private readonly ILogger<V_ProcedureRoleController> _logger;
        private readonly ILes_ProcedureRoleServices _les_ProcedureRoleServices;

        public V_ProcedureRoleController(
            ILes_ProcedureRoleServices les_ProcedureRoleServices,
            IV_ProcedureRoleServices V_ProcedureRoleServices, IUser user, ILogger<V_ProcedureRoleController> logger)
        {
            _V_ProcedureRoleServices = V_ProcedureRoleServices;
            _user = user;
            _logger = logger;
            _les_ProcedureRoleServices = les_ProcedureRoleServices;
        }

        /// <summary> 
        /// 分页获取角色工序查询视图列表 
        /// </summary> 
        /// <param name="param">筛选条件</param> 
        /// <returns>获取结果</returns> 
        [HttpPost]
        public async Task<MessageModel<PageModel<V_ProcedureRoleViewModel>>> Get([FromBody] V_ProcedureRoleParam param)
        {
            if (string.IsNullOrEmpty(param.searchVal) || string.IsNullOrWhiteSpace(param.searchVal))
            {
                param.searchVal = string.Empty;
            }

            var whereConditions = WhereConditionsExtensions.GetWhereConditions<V_ProcedureRole, V_ProcedureRoleParam>(param);
            if (!whereConditions.IsSuccess)
            {
                return new MessageModel<PageModel<V_ProcedureRoleViewModel>>()
                {
                    msg = whereConditions.ErrMsg,
                    success = false,
                    response = null
                };
            }
            var data = await _V_ProcedureRoleServices.QueryPage(whereConditions.data, param.page, param.pageSize, " ModifyTime desc ");
            //转换
            var newQueryData = ListHelper.T1ToT2<PageModel<V_ProcedureRole>, PageModel<V_ProcedureRoleViewModel>>(data);
            if (newQueryData.data != null && newQueryData.data.Count > 0)
            {
                foreach (var item in newQueryData.data)
                {
                    item.AllowProcedureNameList = new List<string>();
                    if (!string.IsNullOrEmpty(item.AllowProcedure))
                    {
                        var arr = item.AllowProcedure.Split(",");
                        foreach (var _ar in arr)
                        {
                            item.AllowProcedureNameList.Add(_ar);
                        }
                    }
                }
            }
            return new MessageModel<PageModel<V_ProcedureRoleViewModel>>()
            {
                msg = "获取成功",
                success = true,
                response = newQueryData
            };

        }

        /// <summary> 
        /// 获取单个角色工序查询视图 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>获取结果</returns> 
        [HttpGet]
        public async Task<MessageModel<V_ProcedureRole>> Get(int id = 0)
        {
            return new MessageModel<V_ProcedureRole>()
            {
                msg = "获取成功",
                success = true,
                response = await _V_ProcedureRoleServices.QueryById(id)
            };
        }


        /// <summary> 
        /// 更新角色工序查询视图 
        /// </summary> 
        /// <param name="request">要更新的角色工序查询视图对象</param> 
        /// <returns>更新结果</returns> 
        [HttpPut]
        public async Task<MessageModel<string>> Put([FromBody] V_ProcedureRoleViewModel request)
        {
            try
            {
                #region 验证 
                MessageModel<string> retBody = null;
                retBody = ValidateDataHelper.CommonValidateIsNULL<V_ProcedureRole, string>(request);
                if (retBody != null)
                {
                    return retBody;
                }

                List<ValidateModel> columnsList = null;
                columnsList = new List<ValidateModel>()
                {
                     new ValidateModel(){ ChinaName="角色ID",PropertyName="RoleId" },
                };
                retBody = ValidateDataHelper.CommonValidate<V_ProcedureRole, string>(request, columnsList);
                if (retBody != null)
                {
                    return retBody;
                }
                #endregion

                string insertStr = "";
                if (request.AllowProcedureNameList != null && request.AllowProcedureNameList.Count > 0)
                {
                    foreach (var item in request.AllowProcedureNameList)
                    {
                        insertStr += item + ",";
                    }
                    insertStr = insertStr.Substring(0, insertStr.Length - 1);
                }

                var dbObjs = await _les_ProcedureRoleServices.Query(x => x.RoleId == request.RoleId);
                if (dbObjs == null || dbObjs.Count == 0)
                {
                    Les_ProcedureRole insert_les_ProcedureRole = new Les_ProcedureRole();
                    insert_les_ProcedureRole.CreateTime = insert_les_ProcedureRole.ModifyTime = DateTime.Now;
                    insert_les_ProcedureRole.CreateBy = insert_les_ProcedureRole.ModifyBy = _user.Name;
                    insert_les_ProcedureRole.CreateId = insert_les_ProcedureRole.ModifyId = _user.ID;
                    insert_les_ProcedureRole.OperationRemark = "新增";
                    insert_les_ProcedureRole.Remark = request.Remark;
                    insert_les_ProcedureRole.AllowProcedure = insertStr;
                    insert_les_ProcedureRole.IsHasAllProcedure = request.IsHasAllProcedure;
                    insert_les_ProcedureRole.RoleId = request.RoleId;

                    await _les_ProcedureRoleServices.Add(insert_les_ProcedureRole);
                }
                else if (dbObjs.Count > 1)
                {
                    return MessageModel<string>.Fail("数据存在" + dbObjs.Count + "条，请联系管理员!");
                }
                else
                {
                    var dbObj = dbObjs[0];
                    dbObj.ModifyTime = DateTime.Now;
                    dbObj.ModifyBy = _user.Name;
                    dbObj.ModifyId = _user.ID;
                    dbObj.OperationRemark = "更新";
                    dbObj.Remark = request.Remark;
                    dbObj.AllowProcedure = insertStr;
                    dbObj.IsHasAllProcedure = request.IsHasAllProcedure;

                    await _les_ProcedureRoleServices.Update(dbObj);
                }
                return MessageModel<string>.Success("更新成功", request.Id.ObjToString());
            }
            catch (Exception ex)
            {
                _logger.LogError("更新角色工序查询视图出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("更新角色工序查询视图出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 删除角色工序查询视图 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> Delete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _V_ProcedureRoleServices.QueryById(id);
                    if (detail != null)
                    {
                        data.success = await _V_ProcedureRoleServices.DeleteById(detail.Id);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                    else
                    {
                        return MessageModel<string>.Fail("数据不存在!");
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,角色工序查询视图不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError("删除角色工序查询视图出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("删除角色工序查询视图出现异常:" + ex.Message);
            }
        }

        /// <summary> 
        /// 逻辑删除角色工序查询视图 
        /// </summary> 
        /// <param name="id">主键</param> 
        /// <returns>删除结果</returns> 
        [HttpDelete]
        public async Task<MessageModel<string>> LogicDelete(int id = 0)
        {
            try
            {
                var data = new MessageModel<string>();
                if (id > 0)
                {
                    var detail = await _V_ProcedureRoleServices.QueryById(id);
                    if (detail != null)
                    {
                        detail.ModifyTime = DateTime.Now;
                        detail.ModifyBy = _user.Name;
                        detail.ModifyId = _user.ID;
                        detail.IsDeleted = true;
                        detail.OperationRemark = "删除";
                        data.success = await _V_ProcedureRoleServices.Update(detail);
                        if (data.success)
                        {
                            data.msg = "删除成功";
                            data.response = detail?.Id.ObjToString();
                        }
                    }
                }
                else
                {
                    data.success = false;
                    data.msg = "删除失败,数据不存在";
                }
                return data;
            }
            catch (Exception ex)
            {
                _logger.LogError("逻辑删除角色工序查询视图出现异常,ex:" + JsonConvert.SerializeObject(ex));
                return MessageModel<string>.Fail("逻辑删除角色工序查询视图出现异常:" + ex.Message);
            }
        }
    }
}
